package com.ruoyi.swla2.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import com.ruoyi.swla2.domain.DfqFreeze;
import com.ruoyi.swla2.domain.DmaFreeze;
import com.ruoyi.swla2.model.FreezeDataQueryModel;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.swla2.domain.DyhFreeze;
import com.ruoyi.swla2.service.IDyhFreezeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 大用户冻结数据Controller
 *
 * @author gdqt
 * @date 2023-08-28
 */
@RestController
@RequestMapping("/swla2/freezeDyh")
public class DyhFreezeController extends BaseController {
    @Autowired
    private IDyhFreezeService dyhFreezeService;

    @PreAuthorize("@ss.hasPermi('swla2:freezeDyh:list')")
    @GetMapping("/getDyhOverviewData")
    public AjaxResult getDyhOverviewData(@RequestParam Map<String, Object> paramMap) {
        String areaId = paramMap.get("areaId").toString();
        DyhFreeze df = new DyhFreeze();
        df.setFrozenType("day");
        df.setFreezetime(LocalDate.now().minusDays(1L).toString());
        List<DyhFreeze> totalDyhFreezeDailyList = dyhFreezeService.selectDyhFreezeList(df);

        df.setAreaid(areaId);
        List<DyhFreeze> dyhFreezeDailyList = dyhFreezeService.selectDyhFreezeList(df);

        df.setAreaid(null);
        df.setFrozenType("month");
        df.setFreezetime(LocalDate.now().minusMonths(1L).format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN)));
        List<DyhFreeze> totalDyhFreezeMonthList = dyhFreezeService.selectDyhFreezeList(df);

        df.setAreaid(areaId);
        List<DyhFreeze> dyhFreezeMonthList = dyhFreezeService.selectDyhFreezeList(df);

        double dailyUsed = 0D, dailyTotal = 0D, monthlyUsed = 0D, monthlyTotal = 0D;
        if (CollUtil.isNotEmpty(dyhFreezeDailyList)) {
            DyhFreeze dyhDaily = dyhFreezeDailyList.stream().filter(item -> item.getAreaid().equals(areaId)).findFirst().orElse(null);
            if (dyhDaily != null) {
                dailyUsed = dyhDaily.getFlowDaily() == null ? 0D : dyhDaily.getFlowDaily().doubleValue();
            }
            dailyTotal = totalDyhFreezeDailyList.stream().map(item -> item.getFlowDaily() == null ? 0D : item.getFlowDaily().doubleValue()).mapToDouble(item -> item).sum();
        }

        if (CollUtil.isNotEmpty(dyhFreezeMonthList)) {
            DyhFreeze dyhMonthly = dyhFreezeMonthList.stream().filter(item -> item.getAreaid().equals(areaId)).findFirst().orElse(null);
            if (dyhMonthly != null) {
                monthlyUsed = dyhMonthly.getFlowDaily().doubleValue();
            }
            monthlyTotal = totalDyhFreezeMonthList.stream().map(item -> item.getFlowDaily().doubleValue()).mapToDouble(item -> item).sum();
        }

        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("dailyUsed", dailyUsed);
        resultMap.put("dailyTotal", dailyTotal);
        resultMap.put("monthlyUsed", monthlyUsed);
        resultMap.put("monthlyTotal", monthlyTotal);

        return success(resultMap);
    }

    @PreAuthorize("@ss.hasPermi('swla2:freezeDyh:list')")
    @GetMapping("/getDyhSupplyAnalysisData")
    public AjaxResult getDyhSupplyAnalysisData(@RequestParam Map<String, Object> paramMap) {
        Map<String, Object> resultMap = new HashMap<>();

        String startDate, endDate;
        Object queryDates = paramMap.get("queryDates");
        if (queryDates == null) {
            startDate = LocalDate.now().minusMonths(12L).format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN));
            endDate = LocalDate.now().minusMonths(1L).format(DateTimeFormatter.ofPattern(DatePattern.NORM_MONTH_PATTERN));
        } else {
            String[] dates = queryDates.toString().split(",");
            startDate = dates[0];
            endDate = dates[1];
        }

        FreezeDataQueryModel model = new FreezeDataQueryModel();
        model.setAreaId(paramMap.get("areaId").toString());
        model.setStartDate(startDate);
        model.setEndDate(endDate);
        model.setFrozenType("month");
        List<DyhFreeze> dfqFreezeList = dyhFreezeService.selectDyhFreezeByQueryModel(model);
        dfqFreezeList.sort(Comparator.comparing(DyhFreeze::getFreezetime));

        resultMap.put("timeList", dfqFreezeList.stream().map(DyhFreeze::getFreezetime).collect(Collectors.toList()));
        resultMap.put("supply", dfqFreezeList.stream().map(item -> item.getFlowDaily().doubleValue()).collect(Collectors.toList()));
        resultMap.put("hb", dfqFreezeList.stream().map(DyhFreeze::getHb).collect(Collectors.toList()));

        return AjaxResult.success(resultMap);
    }

    @PreAuthorize("@ss.hasPermi('swla2:freezeDyh:list')")
    @GetMapping("/listByQueryModel")
    public TableDataInfo listByQueryModel(FreezeDataQueryModel model) {
        startPage();
        List<DyhFreeze> list = dyhFreezeService.selectDyhFreezeByQueryModel(model);
        return getDataTable(list);
    }

    /**
     * 查询大用户冻结数据列表
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDyh:list')")
    @GetMapping("/list")
    public TableDataInfo list(DyhFreeze dyhFreeze) {
        startPage();
        List<DyhFreeze> list = dyhFreezeService.selectDyhFreezeList(dyhFreeze);
        return getDataTable(list);
    }

    /**
     * 导出大用户冻结数据列表
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDyh:export')")
    @Log(title = "大用户冻结数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FreezeDataQueryModel model) {
        List<DyhFreeze> list = dyhFreezeService.selectDyhFreezeByQueryModel(model);
        list.forEach(dyhFreeze -> {
            dyhFreeze.setAreaName(dyhFreeze.getZone().getAreaName());
        });
        ExcelUtil<DyhFreeze> util = new ExcelUtil<DyhFreeze>(DyhFreeze.class);
        util.exportExcel(response, list, "大用户冻结数据数据");
    }

    /**
     * 获取大用户冻结数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDyh:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(dyhFreezeService.selectDyhFreezeById(id));
    }

    /**
     * 新增大用户冻结数据
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDyh:add')")
    @Log(title = "大用户冻结数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DyhFreeze dyhFreeze) {
        dyhFreeze.setTenantId(this.getTenantId());
        return toAjax(dyhFreezeService.insertDyhFreeze(dyhFreeze));
    }

    /**
     * 修改大用户冻结数据
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDyh:edit')")
    @Log(title = "大用户冻结数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DyhFreeze dyhFreeze) {
        return toAjax(dyhFreezeService.updateDyhFreeze(dyhFreeze));
    }

    /**
     * 删除大用户冻结数据
     */
    @PreAuthorize("@ss.hasPermi('swla2:freezeDyh:remove')")
    @Log(title = "大用户冻结数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(dyhFreezeService.deleteDyhFreezeByIds(ids));
    }
}
